<template>
    <div>
        <Header />
        <div class="shopCarSty">
            <div class="title">购物车（全部 {{this.tableDate.length}}）</div>
            <el-table ref="multipleTable" :data="tableDate" tooltip-effect="dark" style="width: 100%;margin-bottom:10px" @selection-change="handleSelectionChange">
                <el-table-column type="selection" align="center" width="60">
                </el-table-column>
                <!-- <el-table-column align="center" label="序号" type="index" width="60">
            </el-table-column> -->
                <el-table-column align="center" label="" width="120">
                    <template slot-scope="scope">
                        <img :src="scope.row.cover" alt="" height="50px">
                    </template>
                </el-table-column>
                <el-table-column prop="name" align="center" label="商品名称" min-width="100">
                    <template slot-scope="scope">
                        《{{ scope.row.name}}》
                    </template>
                </el-table-column>
                <el-table-column prop="price" align="center" label="单价" min-width="80">
                    <template slot-scope="scope">
                        ￥{{ scope.row.price}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="数量" min-width="110">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.num" size="small" @change="handleNumChange(scope.row)" :min="1" :max="999999"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="totalPrice" align="center" label="金额" min-width="80">
                    <template slot-scope="scope">
                        <span style="color:red">￥ {{ scope.row.totalPrice }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" min-width="100">
                    <template slot-scope="scope">
                        <el-button style="color:#F56C6C" type="text" size="small" @click="deleteSelection(0,scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>

            </el-table>
            <div class="footBtn">
                <el-button type="danger" :disabled="!selectedIds.length" size="small" @click="deleteSelection(1)">批量删除</el-button>
                <div class="rightBtn">
                    <div>
                        <span>合计（不含运费）：</span>
                        <span style="font-size:22px;margin-right:20px">{{finalPrice}} 元</span>
                    </div>
                    <el-button type="primary" :disabled="!selectedIds.length" size="small" @click="checkoutBtn">去结算</el-button>
                </div>
            </div>
        </div>
        <Footer />
    </div>

</template>

<script>
import { get, post, del , delJSON} from "@/utils/request";
import Header from "@/views/Components/Header/index.vue";
import Footer from "@/views/Components/Footer/index.vue";
export default {
    data() {
        return {
            tableDate: [],
            selectOption: [],
            selectedIds: [],
            finalPrice: 0,
        };
    },
    components: {
        Header,
        Footer,
    },
    created() {
        this.queryShopCarList();
    },
    watch: {
        selectOption(newVal, oldVal) {
            let arr = [];
            let numP = 0;
            this.selectOption.forEach((item) => {
                numP += item.price * item.num;
                arr.push(item.id);
            });
            this.finalPrice = numP.toFixed(2) * 1;
            this.selectedIds = arr;
        },
    },
    methods: {
        handleSelectionChange(val) {
            this.selectOption = val;
        },
        // 查询购物车列表
        queryShopCarList() {
            this.tableDate = [];
            get("/shopCar/").then((res) => {
                if (res && res.data) {
                    res.data.forEach((item) => {
                        item.totalPrice =
                            (item.price * item.num).toFixed(2) * 1;
                    });
                    this.tableDate = res.data;
                    console.log("购物车list", this.tableDate);
                }
            });
        },
        // 删除购物车
        deleteSelection(num, val) {
            let ids = [];
            if (num === 1) {
                ids = this.selectedIds;
            } else {
                ids[0] = val;
            }

            this.$confirm("此操作将删除该条购物车信息, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    delJSON("/shopCar/", ids).then((res) => {
                        if (res && res.message == "ok") {
                            this.$message({
                                message: "删除成功！",
                                type: "success",
                            });
                            this.queryShopCarList();
                        }
                    });
                })
                .catch(() => {
                    this.$message.error("删除失败！");
                });
        },
        // 结算
        checkoutBtn() {
            sessionStorage.setItem(
                "selectOption",
                JSON.stringify(this.selectOption)
            );
            this.$router.push({
                path: "/settlement",
            });
        },
        // 商品数量发生变化
        handleNumChange(val) {
            val.totalPrice = (val.price * val.num).toFixed(2) * 1;
            put(`/shopCar/${val.id}/${val.num}`).then((res) => {
                if (res && res.message == "ok") {
                    console.log("商品数量已变化");
                    this.queryShopCarList();
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.shopCarSty {
    min-height: calc(100vh - 300px);
    .title {
        height: 50px;
        line-height: 50px;
        font-size: 20px;
        font-weight: 700;
        color: #333;
        margin: 10px 0;
    }
    width: 80%;
    margin: 0 auto;
    .footBtn {
        margin: 10px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .rightBtn {
            display: flex;
            align-items: center;
        }
    }
}
</style>
